package com.android.support.lib.universal.view.gamepad;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.android.support.lib.universal.listenner.TouchpadListener;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 多点触摸板控件(如果设置了背景图片，图片透明区域会隐藏触摸点)
 */
public class TouchpadView extends View {

    class Point {
        private int x;
        private int y;
        //是否隐藏触摸点
        Boolean BHidden = false;
    }

    //半径
    float radius = 30;
    float maxRadius = 45;
    float minRadius = 25;
    //是否变大
    Boolean BBig = true;
    //记录触摸点个数
    Map<Integer, Point> map = new HashMap<>();

    //是否显示画布的内容
    private boolean BShow = false;

    private Paint mPaint;

    private TouchpadListener mTouchpadListener;

    public TouchpadView(Context context) {
        this(context, null);
    }

    public TouchpadView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TouchpadView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mPaint = new Paint();
    }

    //设置触摸板事件
    public void setTouchpadListener(TouchpadListener touchpadListener) {
        mTouchpadListener = touchpadListener;
    }

    @Override
    public void onDraw(Canvas canvas) {
        //触摸状态下，根据触摸点的个数画圆
        if (BShow) {
            //mPaint.setARGB(100, 255, 0, 255);
            mPaint.setColor(Color.parseColor("#ffff5151"));
            mPaint.setAntiAlias(true);// 设置抗锯齿效果
            canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
            Iterator it = map.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                Point point = (Point) entry.getValue();
                if (!point.BHidden) {
                    canvas.drawCircle(point.x, point.y, radius, mPaint);
                }
            }
            //实现圆点渐大渐小效果
            if (BBig) {
                radius = radius + 0.5f;
            } else {
                radius = radius - 0.5f;
            }
            if (radius > maxRadius || radius < minRadius) {
                BBig = !BBig;
            }
        }
        super.onDraw(canvas);
    }

    //是否使用默认颜色样式。
    Boolean BDefaultBG = false;
    //背景位图
    Bitmap bitmap = null;

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        switch (event.getAction() & MotionEvent.ACTION_MASK) {

            case MotionEvent.ACTION_DOWN:
                //触摸时颜色变化（如果控件没有添加背景样式，则使用颜色样式）
                if (getBackground() == null || BDefaultBG) {
                    BDefaultBG = true;
//                    setBackgroundColor(Color.parseColor("#15ff5151"));
                    bitmap = null;
                } else {
                    BDefaultBG = false;
                    if (bitmap == null) {
                        try {
                            BitmapDrawable mBitmapDrawable = (BitmapDrawable) getBackground().getCurrent();
                            bitmap = mBitmapDrawable.getBitmap();
                            //设置位图的宽度和高度等价于当前控件的高度和宽度。即对准像素触摸点。
                            bitmap = Bitmap.createScaledBitmap(bitmap, getWidth(), getHeight(), false);
                        } catch (Exception e) {
                            bitmap = null;
                            Log.e("test", "触摸板背景转化位图失败" + e.getMessage());
                        }
                    }
                }
            case MotionEvent.ACTION_POINTER_DOWN:
                //记录当前触摸点
                map.put(event.getPointerId(event.getActionIndex()), new Point());
            case MotionEvent.ACTION_MOVE:
                BShow = true;
                //实时记录每个触摸点的坐标
                for (int i = 0; i < event.getPointerCount(); i++) {
                    map.get(event.getPointerId(i)).x = Math.round(event.getX(i));
                    map.get(event.getPointerId(i)).y = Math.round(event.getY(i));
                    if (bitmap != null && event.getX(i) + 10 < bitmap.getWidth() && event.getX(i) > 0 && event.getY(i) + 10 < bitmap.getHeight() && event.getY(i) > 0) {
                        //获取当前位图像素点，getPixel(),x,y>=0,且<bitmap本身的宽和高。
                        int pixel = bitmap.getPixel(Math.round(event.getX(i)), Math.round(event.getY(i)));
                        if (pixel == 0) {
                            //像素点为0，当前区域为透明区。隐藏触摸点。
                            map.get(event.getPointerId(i)).BHidden = true;
                        } else {
                            map.get(event.getPointerId(i)).BHidden = false;
                        }
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                //透明
                if (BDefaultBG) {
                    setBackgroundColor(Color.parseColor("#00000000"));
                }
                //最后一个手指离开屏幕时，清除所有记录的触摸点。
                map.clear();
                BShow = false;
            case MotionEvent.ACTION_POINTER_UP:
            case MotionEvent.ACTION_CANCEL:
                //移除离开的触摸点
                map.remove(event.getPointerId(event.getActionIndex()));
                break;
        }
        if (mTouchpadListener != null) {
            mTouchpadListener.onTouchpadMotionEvent(event);
        }
        //刷新View的,必须是在UI线程中
        invalidate();
        return true;
    }

}
